import Toast from 'tdesign-miniprogram/toast/index';
import {
  loginByCode,
  getUserInfo
} from '../../services/user/index'
const menuData = [
  [{
      title: '我参与活动',
      tit: '',
      url: '',
      type: 'activity',
    },
    {
      title: '我的校友会',
      tit: '',
      url: '',
      type: 'origin',
    },
    {
      title: '个人信息',
      tit: '',
      url: '',
      type: 'userInfo',
    },
  ]
];

const getDefaultData = () => ({
  showMakePhone: false,
  userInfo: {
    avatar: '',
    nickName: '正在登录...',
    phone: '',
  },
  menuData,
  customerServiceInfo: {},
  currAuthStep: 1,
  showKefu: true,
  versionNo: '',
  openId: wx.getStorageSync('openid')
});

Page({
  data: getDefaultData(),

  onLoad() {
    this.getVersionInfo();
  },

  onShow() {
    this.getTabBar().init();
    this.init();
  },

  init() {
    const openId = this.data.openId;
    if (!openId) return;
    wx.showLoading()
    getUserInfo(openId).then(res => {
      if (res.data.code === 200 && res.data.data) {
        this.setData({
          userInfo: res.data.data,
          currAuthStep: 2
        })
      }
      wx.setStorageSync('openid', this.data.openId)
      wx.hideLoading()
    })
  },

  onClickCell({
    currentTarget
  }) {
    const {
      type
    } = currentTarget.dataset;

    switch (type) {
      case 'activity': {
        wx.navigateTo({
          url: '/pages/usercenter/activityList/activityList'
        });
        break;
      }
      case 'service': {
        this.openMakePhone();
        break;
      }
      case 'origin': {
        wx.navigateTo({
          url: "/pages/usercenter/alumniaList/alumniaList"
        });
        break;

      }
      case 'userInfo': {
        if (!this.data.openId) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请先登录'
          });
          return
        }
        wx.navigateTo({
          url: `/pages/usercenter/person-info/index?openId=${this.data.openId}`
        });
        break;
      }
      default: {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '未知跳转',
          icon: '',
          duration: 1000,
        });
        break;
      }
    }
  },

  jumpNav(e) {
    const status = e.detail.tabType;

    if (status === 0) {
      wx.navigateTo({
        url: '/pages/order/after-service-list/index'
      })
    } else {
      wx.navigateTo({
        url: `/pages/order/order-list/index?status=${status}`
      });
    }
  },

  openMakePhone() {
    this.setData({
      showMakePhone: true
    });
  },

  closeMakePhone() {
    this.setData({
      showMakePhone: false
    });
  },

  call() {
    wx.makePhoneCall({
      phoneNumber: this.data.customerServiceInfo.servicePhone,
    });
  },

  gotoUserEditPage() {
    const {
      currAuthStep
    } = this.data;
    if (currAuthStep == 1) {
      wx.showLoading();
      wx.login().then(res => {
        if (res.errMsg == 'login:ok') {
          this.setData({
            currAuthStep: 2
          })
          loginByCode(res.code).then(res => {
            if (res.data.code == 200) {
              const {
                session_key,
                openid
              } = res.data.wxLoginInfo;
              if (openid && session_key) {
                wx.getSetting({
                  success: (res) => {
                    console.log(res)
                    if (res.authSetting['scope.userInfo']) {
                      wx.getUserInfo().then(res => {
                        if (res.errMsg == 'getUserInfo:ok') {
                          this.setData({
                            openId: openid
                          })
                          getUserInfo(openid).then(res => {
                            if (res.data.code === 200 && res.data.data) {
                              this.setData({
                                openId: openid,
                                userInfo: res.data.data,
                                currAuthStep: 2
                              })
                               wx.setStorageSync('openid', this.data.openId)
                            } else {
                              wx.navigateTo({
                                url: `/pages/usercenter/person-info/index?openId=${openid}`
                              });
                            }
                            wx.hideLoading()
                          })
                        
                          
                          // 保存用户信息
                          // updateUserInfo({
                          //   ...userInfo,
                          //   openId: openid,
                          //   avatar: userInfo.avatarUrl
                          // }).then(res => {
                          //   if (res.data.code == 200) {
                          //     wx.hideLoading();
                          //   }
                          // })

                          // decryptCode({
                          //   encryptedData,
                          //   iv,
                          //   session_key
                          // }).then(res => {
                          //   console.log(res);
                          // })
                        }

                      })
                    }
                  }
                })
              }
            }
          })
        }
        console.log(res)
      })
    }
    if (currAuthStep === 2) {
      wx.navigateTo({
        url: `/pages/usercenter/person-info/index?openId=${this.data.openId}`
      });
    }
  },

  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const {
      version,
      envVersion = __wxConfig
    } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },
});